<template>
  <ele-page flex-table>
    <ComHeader :title="isUpdate ? `编辑调拨异常单[${info.order_sn}]` : '新增调拨异常单'" @back="goBack" />
    <ele-bottom-bar :teleported="true">
      <template #extra>
        <el-button type="primary" :loading="loading" @click="save">保存</el-button>
      </template>
    </ele-bottom-bar>

    <el-scrollbar flex-table>
      <ele-card>
        <el-descriptions title="" :column="4">
          <el-descriptions-item :width="100" label="调拨异常单">
            <ele-copyable>{{ info.order_sn }}</ele-copyable>
          </el-descriptions-item>
          <el-descriptions-item :width="100" label="调拨单">
            <ele-copyable>{{ info.ot_sn }}</ele-copyable>
          </el-descriptions-item>
          <el-descriptions-item :width="100" label="出库单">
            <ele-copyable>{{ info.out_sn }}</ele-copyable>
          </el-descriptions-item>
          <el-descriptions-item :width="100" label="入库单">
            <ele-copyable>{{ info.enter_sn }}</ele-copyable>
          </el-descriptions-item>
          <el-descriptions-item :width="100" label="订单状态">
            <el-tag :type="getType(info.status)">{{ info.status_name || '-' }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item :width="100" label="货主">
            {{ info.supplier_name || '-' }}
          </el-descriptions-item>
          <el-descriptions-item :width="100" label="发货仓库">
            {{ info.out_warehouse_name || '-' }}
          </el-descriptions-item>
          <el-descriptions-item :width="100" label="收货仓库">
            {{ info.enter_warehouse_name || '-' }}
          </el-descriptions-item>
          <el-descriptions-item :width="100" label="发货数量">
            {{ info.out_num || '-' }}
          </el-descriptions-item>
          <el-descriptions-item :width="100" label="最新发货数量">
            {{ info.new_out_num || '-' }}
          </el-descriptions-item>
          <el-descriptions-item v-if="info.out_status_name" :width="100" label="发货状态">
            <el-tag :type="getType(info.out_status)">{{ info.out_status_name }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item :width="100" label="收货数量">
            {{ info.enter_num || '-' }}
          </el-descriptions-item>
          <el-descriptions-item :width="100" label="最新收货数量">
            {{ info.new_enter_num || '-' }}
          </el-descriptions-item>
          <el-descriptions-item v-if="info.enter_status_name" :width="100" label="收货状态">
            <el-tag :type="getType(info.enter_status)">{{ info.enter_status_name }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item :width="100" label="异常数量">
            {{ info.diff_num || '-' }}
          </el-descriptions-item>
          <el-descriptions-item :width="100" label="最新异常数量">
            {{ info.new_diff_num || '-' }}
          </el-descriptions-item>
          <el-descriptions-item :span="2" label="备注">
            {{ info.remark || '-' }}
          </el-descriptions-item>
        </el-descriptions>
      </ele-card>
      <ele-card>
        <el-form
          ref="formRef"
          label-suffix=""
          class="overflow-hidden"
          :model="form"
          :rules="rules"
          label-width="auto"
          inline-message
        >
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" autosize clearable placeholder="请填写备注" />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="附件" prop="enclosure">
                <FileUpload v-model="form.enclosure" :limit="8" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="商品信息" label-position="top" label-width="200px" prop="product">
                <template #label>
                  <span class="flex-inline items-center">
                    <div class="">商品信息</div>
                  </span>
                </template>
                <el-table
                  ref="tableRef"
                  :data="form.product"
                  size=""
                  border
                  style="width: 100%"
                  show-summary
                  :summary-method="getSummaries"
                >
                  <el-table-column type="index" label="序" width="60" align="center" />
                  <el-table-column prop="product_name" label="商品名称" align="left" min-width="130" />
                  <el-table-column prop="product_code" label="商品编码" align="center" />
                  <el-table-column prop="unit" label="主单位" align="center" />
                  <el-table-column prop="diff_num" label="差异数量" align="center" />
                  <el-table-column
                    prop="new_out_num"
                    label="发货数量"
                    align="center"
                    min-width="130"
                  >
                    <template #default="{ row, $index }">
                      <el-form-item :label-width="0" :prop="`product[${$index}].new_out_num`" :rules="[{ required: true, message: '不能为空' }, { validator: (rule, value, callback) => isEq(row, callback), message: '出入库数量需相等' }]">
                        <div class="flex-1 flex-ca">
                          <div>{{ row.out_num }}</div>
                          <el-icon class="mx-10px"><IconElDArrowRight class="text-primary font-bold" /></el-icon>
                          <el-input
                            v-model="row.new_out_num"
                            class="w-100px!"
                            placeholder="数量"
                            oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                            @change="value => row.new_enter_num = value"
                          >
                            <template #suffix><span class="text-#333!">{{ row.unit }}</span></template>
                          </el-input>
                        </div>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="new_enter_num"
                    label="收货数量"
                    align="center"
                    min-width="130"
                  >
                    <template #default="{ row, $index }">
                      <el-form-item :label-width="0" :prop="`product[${$index}].new_enter_num`" :rules="[{ required: true, message: '不能为空' }, { validator: (rule, value, callback) => isEq(row, callback), message: '出入库数量需相等' }]">
                        <div class="flex-1 flex-ca">
                          <div>{{ row.out_num }}</div>
                          <el-icon class="mx-10px"><IconElDArrowRight class="text-primary font-bold" /></el-icon>

                          <el-input
                            v-model="row.new_enter_num"
                            class="w-100px!"
                            placeholder="数量"
                            oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                            @change="value => row.new_out_num = value"
                          >
                            <template #suffix><span class="text-#333!">{{ row.unit }}</span></template>
                          </el-input>
                        </div>
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </ele-card>
    </el-scrollbar>
  </ele-page>
</template>

<script setup>
import FileUpload from '@/components/FileUpload/index.vue'

defineOptions({ name: 'TransferDiffEdit' })
const route = useRoute()
const router = useRouter()

const { routeTabKey, removePageTab, setPageTabTitle } = utils.usePageTab()

const formRef = ref(null)
const tableRef = ref(null)

const { totalUnit, getType } = utils

const orderId = ref(0)

/** 是否是修改 */
const isUpdate = computed(() => orderId.value > 0)

const loading = ref(false)

const info = ref({})

function isEq(row, callback) {
  if (utils.Big(row.new_out_num).eq(row.new_enter_num)) {
    callback()
  }
  else {
    callback(new Error('出入库数必须相等!'))
  }
}

/** 表单数据 */
const [form, resetFields, assignFields] = utils.useFormData({
  id: undefined,
  order_date: '',
  supplier_id: '',
  out_warehouse_id: '',
  enter_warehouse_id: '',
  enclosure: '',
  num: '',
  remark: '',
  product: [],
})

/** 表单验证规则 */
const rules = reactive({
  product: {
    required: true,
    message: '请选择商品',
    type: 'array',
    trigger: 'change',
    min: 1,
  },
})

function goBack() {
  removePageTab({ key: routeTabKey })
  router.push('/transfer/diff')
}

onMounted(() => {
  orderId.value = Number(route.params?.id)

  if (orderId.value) {
    getInfo()
  }
  else {
    setPageTabTitle('新增调拨异常单')
  }
})

function getInfo() {
  utils.get('/transfer/diffInfo', { id: orderId.value }).then((res) => {
    info.value = res.data
    setPageTabTitle(`编辑调拨异常单[${utils.ellipsisStr(res.data.order_sn, 0, 10)}]`)
    assignFields({
      ...form,
      ...res.data,
      enclosure: utils.encodeFiles(res.data.enclosure),
    })
  })
}

function save() {
  formRef.value?.validate?.((valid) => {
    if (!valid)
      return

    loading.value = true

    const formData = {
      id: info.value.id,
      remark: form.remark,
      enclosure: utils.decodeFiles(form.enclosure),
      product: form.product.map(v => ({
        id: v.id,
        product_code: v.product_code,
        product_name: v.product_name,
        new_enter_num: v.new_enter_num,
        new_out_num: v.new_out_num,
      })),
    }

    utils.post('/transfer/diffEdit', formData)
      .then((res) => {
        utils.message(res.msg, res.success)
        if (res.success) {
          goBack()
        }
      })
      .finally(() => {
        loading.value = false
      })
  })
}

function getSummaries({ columns, data }) {
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const keys = ['multi_unit']
    if (keys.includes(column.property)) {
      sums[index] = data.reduce((acc, cur) => {
        const value = column.property === 'multi_unit' ? totalUnit(cur[column.property]) : cur[column.property]
        return utils.Big(acc).plus(value).valueOf()
      }, 0)
    }
    else {
      sums[index] = ''
    }
  })

  return sums
}
</script>

<style lang="scss" scoped></style>
